package com.mysiteforme.admin.controller.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import com.mysiteforme.admin.entity.base.ChImage;
import com.mysiteforme.admin.entity.user.ChPayment;
import com.mysiteforme.admin.realm.AuthRealm;
import com.mysiteforme.admin.service.base.ChImageService;
import com.mysiteforme.admin.service.user.ChPaymentService;
import com.mysiteforme.admin.util.IdWorker;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.QiNiuGetExamToken;
import com.mysiteforme.admin.util.RestResponse;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yj
 * @since 2019-04-29
 */
@Controller
@RequestMapping("/chPayment")
public class ChPaymentController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ChPaymentController.class);

    @Resource
    private QiNiuGetExamToken qiNiuGetExamToken;

    @Autowired
    private ChPaymentService chPaymentService;

    @Resource
    private ChImageService chImageService;
    //设置好账号的ACCESS_KEY和SECRET_KEY
    @Value("${qiniu.token.ak}")
    String ACCESS_KEY;
    @Value("${qiniu.token.sk}")
    String SECRET_KEY;

    //要上传的空间
    @Value("${qiniu.token.image_bucket}")
    String bucketname;

    @GetMapping("list")
    @SysLog("跳转列表")
    public String list() {
        return "/ytzluser/chPayment/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求列表数据")
    public LayerData<ChPayment> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                     ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "");
        LayerData<ChPayment> layerData = new LayerData<>();
        EntityWrapper<ChPayment> wrapper = new EntityWrapper<>();
        if (!map.isEmpty()) {
            wrapper.isWhere(true);
            if (map.get("searchInfo") != null && map.get("searchInfo") != "") {
                wrapper.like("p.user_number", (String) map.get("searchInfo"));
                wrapper.orNew().like("u.real_name", (String) map.get("searchInfo"));
            }
            if (map.get("paymentType") != null && map.get("paymentType") != "") {
                wrapper.eq("p.payment_type", Integer.parseInt((String) map.get("paymentType")));
            }
            if (map.get("paymentMode") != null && map.get("paymentMode") != "") {
                wrapper.eq("p.payment_mode", Integer.parseInt((String) map.get("paymentMode")));
            }
            if (map.get("paymentTerm") != null && map.get("paymentTerm") != "") {
                wrapper.eq("p.payment_term", Integer.parseInt((String) map.get("paymentTerm")));
            }
        }
        Page<ChPayment> pageData = chPaymentService.selectByEntityWrapper(new Page<>(page, limit), wrapper);
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @GetMapping("add")
    @SysLog("跳转新增页面")
    public String add() {
        return "/ytzluser/chPayment/add";
    }

    @PostMapping("add")
    @SysLog("保存新增数据")
    @ResponseBody
    public RestResponse add(ServletRequest request) throws ParseException {
        Map map = WebUtils.getParametersStartingWith(request, "");
        System.out.println("======进来了" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNowTime")));
        ChPayment chPayment = new ChPayment();
        chPayment.setId(IdWorker.getId());
        chPayment.setPayeeName(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getNickName());
        if (map.get("paymentNowTime") != null && map.get("paymentNowTime") != "") {
            chPayment.setPaymentNowTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNowTime")));
        }
        if (map.get("paymentNextTime") != null && map.get("paymentNextTime") != "") {
            chPayment.setPaymentNextTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNextTime")));
        } else {
            chPayment.setPaymentNextTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNowTime")));
        }

        if (map.get("paymentMoney") != null && map.get("paymentMoney") != "") {
            long paymentMoney = Long.parseLong((String) map.get("paymentMoney"));
            chPayment.setPaymentMoney(paymentMoney * 100);
        }

        if (map.get("paymentSpareMoney") != null && map.get("paymentSpareMoney") != "") {
            long paymentSpareMoney = Long.parseLong((String) map.get("paymentSpareMoney"));
            chPayment.setPaymentSpareMoney(paymentSpareMoney * 100);
        } else
            chPayment.setPaymentSpareMoney(Long.parseLong("0"));

        if (map.get("paymentTerm") != null && map.get("paymentTerm") != "") {
            chPayment.setPaymentTerm(Integer.parseInt((String) map.get("paymentTerm")));
        }

        if (map.get("userNumber") != null && map.get("userNumber") != "") {
            chPayment.setUserNumber((String) map.get("userNumber"));
        }

        if (map.get("paymentMode") != null && map.get("paymentMode") != "") {
            chPayment.setPaymentMode(Integer.parseInt((String) map.get("paymentMode")));
        }

        if (map.get("paymentType") != null && map.get("paymentType") != "") {
            chPayment.setPaymentType(Integer.parseInt((String) map.get("paymentType")));
        }

        if (map.get("receivablesId") != null && map.get("receivablesId") != "") {
            chPayment.setReceivablesId((String) map.get("receivablesId"));
        } else
            chPayment.setReceivablesId(" ");

        chPayment.setCreationDate(new Date());
        chPayment.setCreationBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        chPayment.setPayeeName(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getNickName());

        if (map.get("imageUrl") != null && map.get("imageUrl") != "" && !((String) map.get("imageUrl")).equals("new")) {
            LOGGER.info("添加账单图片信息：------------------------------{}" + (String) map.get("imageUrl"));
            ChImage chImage = new ChImage();
            chImage.setId(IdWorker.getId());
            chImage.setTargetId(chPayment.getId());
            chImage.setType(2);
            chImage.setPosition(0);
            chImage.setImageUrl((String) map.get("imageUrl"));
            chImage.setCreationDate(new Date());
            chImageService.addBillImage(chImage);
        }

        boolean add = chPaymentService.insertPayment(chPayment);
        if (add) return RestResponse.success();
        else return RestResponse.failure("数据库繁忙！！！");
    }

    @RequestMapping("toedit")
    @SysLog("跳转编辑页面")
    public String edit() {
        return "/ytzluser/chPayment/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑数据")
    public RestResponse edit(ServletRequest request) throws ParseException {
        Map map = WebUtils.getParametersStartingWith(request, "");
        ChPayment chPayment = new ChPayment();
        chPayment.setId((String) map.get("id"));
        if (map.get("paymentNowTime") != null && map.get("paymentNowTime") != "") {
            chPayment.setPaymentNowTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNowTime")));
        }
        if (map.get("paymentNextTime") != null && map.get("paymentNextTime") != "") {
            chPayment.setPaymentNextTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNextTime")));
        } else {
            chPayment.setPaymentNextTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) map.get("paymentNowTime")));
        }

        if (map.get("paymentMoney") != null && map.get("paymentMoney") != "") {
            long paymentMoney = Long.parseLong((String) map.get("paymentMoney"));
            chPayment.setPaymentMoney(paymentMoney * 100);
        }

        if (map.get("paymentSpareMoney") != null && map.get("paymentSpareMoney") != "") {
            long paymentSpareMoney = Long.parseLong((String) map.get("paymentSpareMoney"));
            chPayment.setPaymentSpareMoney(paymentSpareMoney * 100);
        } else
            chPayment.setPaymentSpareMoney(Long.parseLong("0"));

        if (map.get("paymentTerm") != null && map.get("paymentTerm") != "") {
            chPayment.setPaymentTerm(Integer.parseInt((String) map.get("paymentTerm")));
        }

        if (map.get("userNumber") != null && map.get("userNumber") != "") {
            chPayment.setUserNumber((String) map.get("userNumber"));
        }

        if (map.get("paymentMode") != null && map.get("paymentMode") != "") {
            chPayment.setPaymentMode(Integer.parseInt((String) map.get("paymentMode")));
        }

        if (map.get("paymentType") != null && map.get("paymentType") != "") {
            chPayment.setPaymentType(Integer.parseInt((String) map.get("paymentType")));
        }

        if (map.get("receivablesId") != null && map.get("receivablesId") != "") {
            chPayment.setReceivablesId((String) map.get("receivablesId"));
        } else
            chPayment.setReceivablesId(" ");

        chPayment.setModifyedDate(new Date());
        chPayment.setModifyedBy(((AuthRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal()).getId().toString());
        if (map.get("imageUrl") != null && map.get("imageUrl") != "" && !((String) map.get("imageUrl")).equals("new")) {
            LOGGER.info("编辑账单图片信息：------------------------------{}" + (String) map.get("imageUrl"));
            ChImage chImage = new ChImage();
            chImage.setTargetId(chPayment.getId());
            chImage.setType(2);
            chImage.setPosition(0);
            chImage.setImageUrl((String) map.get("imageUrl"));
            chImage.setModifyDate(new Date());
            chImageService.updateBillImage(chImage);
        }

        boolean update = chPaymentService.updatePaymentById(chPayment);
        if (update) return RestResponse.success();
        else return RestResponse.failure("系统繁忙");

    }

    @RequestMapping("check")
    @SysLog("跳转到验证页面")
    public String check() {
        return "/ytzluser/chPayment/check";
    }

    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除数据")
    public RestResponse delete(@RequestParam(value = "id", required = false) String id) {
        if (null == id || "" == id) {
            return RestResponse.failure("ID不能为空");
        }
        Boolean del = chPaymentService.deletePaymentById(id);
        if (del)
            return RestResponse.success();
        else
            return RestResponse.failure("系统繁忙");
    }

    @PostMapping("/examine")
    @ResponseBody
    @SysLog("支付信息审核通过")
    public RestResponse examine(@RequestParam("id") String id) {
        if (null == id || "" == id) {
            return RestResponse.failure("ID不能为空");
        }
        boolean verify = chPaymentService.examine(id);
        if (verify) return RestResponse.success("审核成功");
        else return RestResponse.failure("系统繁忙");
    }

    @PostMapping("/getBillUrl")
    @ResponseBody
    @SysLog("获取题目图片地址")
    public RestResponse getImageUrl(@RequestParam(value = "paymentId", required = true) String paymentId) {
        if (paymentId != null && paymentId != "") {
            String imageUrl = chImageService.getImageUrl(paymentId);
            LOGGER.info("前台获取账单图片地址：------------------------------{}" + imageUrl);
            if (imageUrl == null && imageUrl.trim() == "")
                return RestResponse.failure("暂无图片数据");
            else
                return RestResponse.success().setData(imageUrl);
        } else {
            return RestResponse.failure("账单ID不能为空");
        }

    }

    @PostMapping("getUploadToken")
    @ResponseBody
    @SysLog("七牛云token获取")
    public RestResponse upload(@RequestParam(value = "suffix", required = true) String suffix) {
        if (null == suffix || "" == suffix) {
            return RestResponse.failure("文件格式错误");
        }
        String randomName = "bill/" + IdWorker.getId() + (suffix.contains(".") ? suffix : "." + suffix);
        String token = qiNiuGetExamToken.getUpToken(randomName);
////        Zone z = Zone.zone1();
////        Configuration config = new Configuration(z);
////        UploadManager uploadManager = new UploadManager(config);
//        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//        String token = auth.uploadToken(bucketname);
        Map<String, Object> map = new HashMap<>();
        if (token == null || "" == token) {
            return RestResponse.failure("token获取失败");
        }
        map.put("token", token);
        map.put("filename", randomName);
        System.out.println(map.size());
        return RestResponse.success().setData(map);
    }

    @PostMapping("/deleteBill")
    @ResponseBody
    @SysLog("七牛云删除账单图片")
    public RestResponse deleteBill(@RequestParam(value = "key", required = true) String key) {
        if (!key.isEmpty()) {
//            qiNiuGetExamToken.deleteQiniuP(key);
//            //根据图片名称删除账单图片
//            chImageService.deleteBillImage(key);
            return RestResponse.success();
        } else
            return RestResponse.failure("图片地址为空");
    }

}